package io.chenhd.gateway.filter;

import io.chenhd.gateway.cache.ContextCache;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.util.AttributeKey;

/**
 * Create by chenhd on 2021/8/21.
 */
public class ResponseLogFilter extends ChannelOutboundHandlerAdapter implements HttpResponseFilter {
    @Override
    public void filter(FullHttpResponse response, ChannelHandlerContext context) {
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {

        AttributeKey<String> requestKey = AttributeKey.valueOf("requestId");
        String requestId = ctx.channel().attr(requestKey).get();
        FullHttpResponse fullHttpResponse = (FullHttpResponse) msg;
        ByteBuf byteBuf = fullHttpResponse.content();
        String str;
        if (byteBuf.hasArray()) {
            // 处理堆缓冲区
            str = new String(byteBuf.array(), byteBuf.arrayOffset() + byteBuf.readerIndex(), byteBuf.readableBytes());
        } else {
            // 处理直接缓冲区以及复合缓冲区
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.getBytes(byteBuf.readerIndex(), bytes);
            str = new String(bytes, 0, byteBuf.readableBytes());
        }
        long startTime = ContextCache.contextTimeCache.getOrDefault(requestId, System.currentTimeMillis());
        System.out.println(String.format("requestId %s response: status:%s, content:%s, use time: %dms",
                requestId, fullHttpResponse.status().code(), str, System.currentTimeMillis() - startTime));
        ContextCache.contextTimeCache.remove(requestId);
        super.write(ctx, msg, promise);
    }
}
